package leetcode.code1694;

import java.util.StringJoiner;

public class Solution {
	public String reformatNumber(String number) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < number.length(); i++) {
			char c = number.charAt(i);
			if (c >= '0' && c <= '9') {
				sb.append(c);
			}
		}
		int len = sb.length();
		int div = len / 3;
		int mod = len % 3;
		StringBuffer ans = new StringBuffer();
		for (int i = 0; i < div - 1; i++) {
			if (i > 0) {
				ans.append('-');
			}
			ans.append(sb.subSequence(i * 3, i * 3 + 3));
		}
		if (mod == 1) {
			if (len > 4) {
				ans.append('-');
			}
			ans.append(sb.substring(len - 4, len - 2)).append('-').append(sb.substring(len - 2, len));
		} else if (mod == 2) {
			if (len > 5) {
				ans.append('-');
			}
			if (len > 4) {
				ans.append(sb.substring(len - 5, len - 2)).append('-');
			}
			ans.append(sb.substring(len - 2, len));
		} else {
			if (len > 3) {
				ans.append('-');
			}
			ans.append(sb.substring(len - 3, len));
		}
		return ans.toString();
	}
}
